<template>
<nly-content-wrapper class="funnel">
    <nly-content-header>
        <div class="a-button-bar">
        <nly-row class="col-12 mt-4 mb-4">
            <nly-col xs="12" sm="12" md="12" lg="12" xl="12"  class="form-inline " style="justify-content: left;">
                <form-select
                    title="部门"
                    labelStyle=""
                    rightStyle="width:150px;"
                    class="ml-1 mb-2"
                    showSearch
                    addDefaultText="全部"
                    v-model="officeId"
                    :dataList="officeData"
                    @change="changeOffice"
                ></form-select>
                <form-select
                    title="人员"
                    labelStyle=""
                    rightStyle="width:150px;"
                    class="ml-1 mb-2"
                    showSearch
                    addDefaultText="全部"
                    v-model="userId"
                    :dataList="userData"
                ></form-select>
                <form-rang-date-picker 
                    title="创建时间"
                    size="small"
                    labelStyle=""
                    rightStyle="min-width: 150px; max-width: calc(410px + 0.25rem);"
                    class="ml-1 mb-2"
                    format="YYYY-MM-DD"
                    v-model="rangDateVal"
                ></form-rang-date-picker>
                <div class="mb-1 my_bt_group" style="margin-left: 35px;">
                  <nly-button
                    variant="info"
                    @click="saleFunnelStatistic"
                    button-class="mr-2"
                    >查询</nly-button>
            </div>
          </nly-col>
        </nly-row>
        </div>
    </nly-content-header>
    <nly-content>
        <a-row class="col-xs-12 col-sm-10 col-lg-8 mb-5" style="display:flex;flex:1;">
            <v-chart :options="options"  />
        </a-row>
    </nly-content>

</nly-content-wrapper>
   
</template>



<script>
// import ECharts from 'vue-echarts'

// import "echarts/lib/chart/funnel";
// import "echarts/lib/component/tooltip";
// import "echarts/lib/component/legend";
// import "echarts/lib/component/markPoint";
// import "echarts/lib/component/markLine";
// import "echarts/lib/component/graphic";
// import "echarts/lib/component/title";
// import "echarts/lib/component/toolbox";

import {getDataScopeUsers} from "@/api/user";
import {saleFunnelStatistic} from "@/api/crm/business";
import { listToSelectTree } from "@/utils/tree";



export default {
    name:"salefunnel",
  components: {
    'v-chart': VueECharts
  },
  data () {
    return {
        officeId:"",    //部门id
        userId:"",     //用户Ids
        rangDateVal:[],//时间范围
        //提交的条件 
        PostData:{
            userIds:[],
            startTime:"",   //开始时间
            endTime:""      //结束时间  
        },
        selectedOffice:{key:''},  //当前选择的部门信息
        officeTreeData:[],          //部门树
        officeData:[],      //可以查看的部门权限
        allUsers: [],       //全部用户
        funnelData: [],
        legendData:[],

    }
  },
  computed:{
        options:function(){
            let o =  {
                title: {
                    text: '销售漏斗',
                    subtext: '阶段分布',
                    // textAlign:"middle", 
                    left: 'center',
                    align: 'right'
                },
             
                tooltip: {
                    trigger: 'item',
                    formatter: function (params, ticket, callback) {
                        console.log(params.data);
                        const {name,value,number,money,percentage} = params.data;
                        let showHtm = `销售漏斗<br/>${name}：${percentage}%<br/>数量：${number}<br/>预计收入：${money}`;
                        return showHtm;
                        // "{a} <br/>{b} : {c}%"
                    }
                },
                toolbox: {
                    feature: {
                        restore: {},
                        saveAsImage: {}
                    }
                },
                legend: {
                    // top: "35%",
                    bottom:"0%",
                    // itemHeight: 28,
                    // orient:"vertical",
                    align: "left",
                    data: this.legendData
                },

                series: [
                    {
                        name:'漏斗图',
                        type:'funnel',
                        left: '15%',
                        top: 60,
                        //x2: 80,
                        bottom: 60,
                        width: '70%',
                        // height: {totalHeight} - y - y2,
                        min: 0,
                        max: 100,
                        minSize: '0%',
                        maxSize: '100%',
                        sort: 'descending',
                        gap: 2,
                        label: {
                            show: true,
                            color: "#000",
                            // position: 'inside',
                            formatter: function (params) {
                                console.log(params.data);
                                // const {name,value,number,money,percentage} = params.data;
                                // let showHtm = `${name}：${percentage}%`;
                                // return showHtm;
                                const {name,value,number,money,percentage} = params.data;
                                let showHtm = `${name}：${percentage}%\n商机数量：${number}\n预计收入：${money}`;
                                return showHtm;
                                // "{a} <br/>{b} : {c}%"
                            }
                        },
                        labelLine: {
                            show: true,
                            
                            // length: 1,
                            lineStyle: {
                                color: "#000",
                            }
                        },
                        itemStyle: {
                            // borderColor: '#6c757d',
                            borderColor: '#fff',
                            borderWidth: 1
                        },
                        // emphasis: {
                        //     label: {
                        //         fontSize: 20,
                        //         formatter: function (params) {
                        //             console.log(params.data);
                        //             // const {name,value,number,money,percentage} = params.data;
                        //             // let showHtm = `${name}：${percentage}%`;
                        //             // return showHtm;
                        //             const {name,value,number,money,percentage} = params.data;
                        //             let showHtm = `${name}：${percentage}%\n数量：${number}\n预计收入：${money}`;
                        //             return showHtm;
                        //             // "{a} <br/>{b} : {c}%"
                        //         }
                        //     }
                        // },
                        data: this.funnelData
                    }
                ]
            };
            return o;
        },
        userData:function(){
            const {allUsers,officeData,officeId} = this;
            if(officeId){
                let userIds = officeData.find(f=>f.key == officeId).userIds;
                return userIds;
            }else{
                return allUsers;
            }
        }
  },
  created(){
      console.log("销售漏斗图",this.options)
      this.getDataScopeUsers();
      this.saleFunnelStatistic();
  },

  methods:{
    //销售漏斗
    saleFunnelStatistic(){
        const { PostData , userData ,officeId, userId,rangDateVal}  = this;
        console.log("用户ID",userId,rangDateVal)
        if(rangDateVal.length == 2 && rangDateVal[0]){
            PostData.startTime = rangDateVal[1][0];
            PostData.endTime = rangDateVal[1][1];
        }else{
            PostData.startTime = "";
            PostData.endTime = "";
        }
        if( !userId ){
             PostData.userIds = [];
        }else{
             PostData.userIds = [userId];
        }
        PostData.officeId = officeId;
        saleFunnelStatistic(PostData)
            .then(response => {
            if (response.code === 200) {
                const { data } = response;
                this.funnelData = data;
                this.legendData = data.map(f=>f.name);
            }
            })
            .catch(error => {});
    },
    //权限部门人员
    getDataScopeUsers(){
        getDataScopeUsers()
            .then(response => {
            if (response.code === 200) {
                console.log("漏斗图_获取部门权限人员")
                const { data } = response;
                this.translateOfficeUser(data);
            }
            })
            .catch(error => {});
    },
    //转换数据
    translateOfficeUser(data){
        const {officeData,userData} = data;
        const officeMap = new Map();
        const allUsers = [];
        const otherUsers = [];
        officeData.forEach(f=>{
            const {id,name} = f;
            let key = id;
            let title = name;
            let officeItem = {key,title};
            officeMap.set(key,officeItem);
        });
        userData.forEach(user=>{
            const {officeId,userId,userName} = user;
            const officeItem = officeMap.get(officeId+"");
            let key = userId;
            let title = userName;
            let userItem = {key,title};
            if(officeItem){
                if(!officeItem.userIds){
                    officeItem.userIds = [];
                }
                officeItem.userIds.push(userItem);
            }else{
                otherUsers.push(userItem);
            }
            allUsers.push(userItem);
        });
        this.officeData = [...officeMap.values()];

        let officeTreeData = [];
        listToSelectTree(officeData, officeTreeData,  {
            key: "id",
            title: "name"
        });
        console.log("this.officeTreeData",officeData,officeTreeData)

        Object.assign(this,{allUsers,officeTreeData});
    },
    //
    changeOffice(){
        this.userId = '';
    }

  }
}
</script>

<style lang="less">
.funnel{
    /**
    * 默认尺寸为 600px×400px，如果想让图表响应尺寸变化，可以像下面这样
    * 把尺寸设为百分比值（同时请记得为容器设置尺寸）。
    */
    .echarts {
        width: 100%;
        height: 100%; 
    }

    .my-bt .my_bt_group{
        // flex-grow: 1;
        text-align: end;
    }
}

</style>
